package com.qf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.User;
import com.qf.enums.AppHttpCodeEnum;
import com.qf.exception.SystemException;
import com.qf.mapper.RoleMapper;
import com.qf.mapper.UserMapper;
import com.qf.result.ResponseResult;
import com.qf.service.UserService;
import com.qf.utils.BeanCopyUtils;
import com.qf.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-02-04 22:32:57
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public ResponseResult getUserList() {
        //查询所有员工信息
        List<User> users = list();
        List<UserVo> userVos = BeanCopyUtils.copyBeanList(users, UserVo.class);
        userVos.stream()
//                .map(userVo -> userVo.setRoleName(roleMapper.getRole(userVo.getId()).getRoleName()))
                .map(userVo -> userVo.setRoleName(roleMapper.selectById(userVo.getRoleId()).getRoleName()))
                .collect(Collectors.toList());
        return ResponseResult.okResult(userVos);
    }

    @Override
    public ResponseResult deleteUser(Integer id) {
        if (getById(id) == null) {
            throw new SystemException(AppHttpCodeEnum.ID_ERROR);
        }
        boolean flag = removeById(id);
        if (flag)
            return ResponseResult.okResult();
        return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }

    @Override
    public ResponseResult addUser(User user) {
        boolean flag = save(user);
        if (flag)
            return ResponseResult.okResult();
        return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }

    @Override
    public ResponseResult updateUser(User user) {
        if (getById(user.getId()) == null) {
            throw new SystemException(AppHttpCodeEnum.ID_ERROR);
        }
        boolean flag = updateById(user);
        if (flag)
            return ResponseResult.okResult();
        return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }

}
